package com.dajiba.demo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.widget.Scroller;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class CustomWheelPicker extends BaseCustomView {
    private ArrayList<String> datas = new ArrayList<>();

    public CustomWheelPicker(Context context) {
        this(context, null);
    }

    public CustomWheelPicker(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomWheelPicker(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        scroller = new Scroller(context);
    }

    private void init() {
        for (int i = 0; i < 100; i++) {
            datas.add("哈哈哈哈哈" + i);
            totalTextHeight = totalTextHeight + itemHeight;
        }

        mSelectedItemPaint.setTextSize(txtSize);
        mSelectedItemPaint.setAntiAlias(true);
        mSelectedItemPaint.setColor(txtSelectColor);

        mTextPaint.setTextSize(txtSize);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(txtColor);

        mLinearGradient = new LinearGradient(Color.GRAY, Color.BLACK);
    }

    Scroller scroller;
    int downY;
    int scrollY;
    int curY;
    VelocityTracker velocityTracker;
    boolean isDown = false;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (velocityTracker == null) {
            velocityTracker = VelocityTracker.obtain();
        }
        velocityTracker.addMovement(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int moveY = (int) event.getY() - downY;
                scrollY = curY + moveY;
                mSelectedItemPaint.setColor(txtColor);
                if (scrollY > (getHeight() - itemHeight) / 2) {
                    curY = (getHeight() - itemHeight) / 2;
                    scrollY = (getHeight() - itemHeight) / 2;
                    mSelectedItemPaint.setColor(txtSelectColor);
                }
                if (-scrollY >= totalTextHeight - (getHeight() + itemHeight) / 2) {
                    scrollY = -totalTextHeight + (getHeight() + itemHeight) / 2;
                    mSelectedItemPaint.setColor(txtSelectColor);
                }
                invalidate();
                break;
            case MotionEvent.ACTION_DOWN:
                isDown = true;
                downY = (int) event.getY();
                velocityTracker.clear();
                scroller.abortAnimation();

                break;
            case MotionEvent.ACTION_UP:
                invalidate();
                isDown = false;
                curY = scrollY;
                velocityTracker.computeCurrentVelocity(1000, 20000);
                int velocity = (int) velocityTracker.getYVelocity();
                scroller.fling(0, curY, 0, velocity,
                        0, 0, -20000, 20000);
                handler.post(scrollRun);
                velocityTracker.recycle();
                velocityTracker = null;
                break;
        }
        return true;
    }

    /**
     * 获取当前位置
     *
     * @return
     */
    private int getPosition() {
        return (lineTopX - scrollY) / itemHeight;
    }

    private Handler handler = new Handler();
    private Runnable scrollRun = new Runnable() {
        @Override
        public void run() {
            if (isDown) return;
            if (scroller.computeScrollOffset()) {
                scrollY = curY = scroller.getCurrY();
                if (-scrollY >= totalTextHeight - (getHeight() + itemHeight) / 2) {
                    scrollY = -totalTextHeight + (getHeight() + itemHeight) / 2;
                    mSelectedItemPaint.setColor(txtSelectColor);
                    postInvalidate();
                    return;
                }
                postInvalidate();
                handler.postDelayed(this, 10);
            } else {
                //检查是否选项是否居中
                //中间的位置
                //item偏移量
                int i = (lineTopX - curY) % itemHeight;
                if (i > itemHeight / 2) {
                    i = i - itemHeight;
                }
                scroller.startScroll(0, curY, 0, i, 250);
                handler.post(scrollFixCenterItem);
            }

        }
    };

    private Runnable scrollFixCenterItem = new Runnable() {
        @Override
        public void run() {
            if (scroller.computeScrollOffset()) {
                scrollY = curY = scroller.getCurrY();
                handler.postDelayed(this, 10);
            } else {
                mSelectedItemPaint.setColor(txtSelectColor);
            }
            postInvalidate();
        }
    };

    int txtColor = Color.parseColor("#B4B1B4");
    int txtSelectColor = Color.parseColor("#3D3B3B");

    int lineTopX = 0;
    int lineBottomX = 0;
    int totalTextHeight = 0;
    int itemHeight = 200;
    int txtSize = 60;
    Paint mSelectedItemPaint = new Paint();
    Paint mTextPaint = new Paint();
    LinearGradient mLinearGradient;
    int lineOffset = SizeUtils.dp2px(2);
    boolean isInit = false;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (scrollY > (getHeight() - itemHeight) / 2) {
            curY = (getHeight() - itemHeight) / 2;
            scrollY = (getHeight() - itemHeight) / 2;
            mSelectedItemPaint.setColor(txtSelectColor);
        }
        mPaint.setTextSize(txtSize);
        mPaint.setColor(Color.BLACK);
        int txtCenter = (itemHeight - txtSize) / 2;
        int position = getPosition();
        lineTopX = (getHeight() - itemHeight) / 2 + lineOffset;
        lineBottomX = (getHeight() + itemHeight) / 2 + lineOffset;

        int txtCitiX = getWidth() / 2;

        for (int i = 0; i < datas.size(); i++) {
            int txtY = ((i + 1) * itemHeight) - txtCenter + scrollY;
            float offsetX = mPaint.measureText(datas.get(i)) / 2;
            if (position == i) {
                canvas.drawText(
                        datas.get(i),
                        txtCitiX - offsetX,
                        txtY,
                        mSelectedItemPaint
                );
            } else {
                canvas.drawText(
                        datas.get(i),
                        txtCitiX - offsetX,
                        txtY,
                        mTextPaint
                );
            }
        }

        //画蒙层
        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#E3E1E2"));
        paint.setStrokeWidth(SizeUtils.dp2px(1));
        canvas.drawLine(
                0f,
                (getHeight() - itemHeight) / 2 + lineOffset,
                getWidth(),
                (getHeight() - itemHeight) / 2 + lineOffset,
                paint
        );
        canvas.drawLine(
                0f,
                (getHeight() + itemHeight) / 2 + lineOffset,
                getWidth(),
                (getHeight() + itemHeight) / 2 + lineOffset,
                paint
        );

        if (!isInit) {
            scroller.startScroll(0, curY, 0, lineTopX, 500);
            handler.post(scrollFixCenterItem);
            isInit = true;
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        LogUtils.d("onAttachedToWindow");
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        LogUtils.d("onDetachedFromWindow");
    }
}
